package com.py.payment.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.py.payment.dto.param.PayRecordsParamDto;
import com.py.payment.dto.ret.LineChartRetDto;
import com.py.payment.entity.PyInfo;
import com.py.payment.entity.PyPayRecords;
import com.py.payment.mapper.PyPayRecordsMapper;
import com.py.payment.service.PyPayRecordsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.py.payment.tools.ToolsUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 支付记录 服务实现类
 * </p>
 *
 * @author py
 * @since 2024-04-17
 */
@Service
public class PyPayRecordsServiceImpl extends ServiceImpl<PyPayRecordsMapper, PyPayRecords> implements PyPayRecordsService {

    @Override
    public void addPayMent(PyPayRecords payRecords) {
        QueryWrapper<PyPayRecords> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type",payRecords.getType());
        queryWrapper.eq("info_id",payRecords.getInfoId());
        queryWrapper.orderByDesc("sort");
        queryWrapper.last("limit 1");
        PyPayRecords records = this.getOne(queryWrapper);
        if(ToolsUtils.isNotEmpty(records)){
            payRecords.setSort(records.getSort()+1);
        } else{
            payRecords.setSort(1);
        }
        payRecords.setCreateTime(new Date());
        this.save(payRecords);
    }

    @Override
    public List<PyPayRecords> getPayRecordList(PayRecordsParamDto paramDto) {
        return this.baseMapper.getPayRecordList(paramDto);
    }

    @Override
    public LineChartRetDto getLineChart(PyInfo pyInfo) {
        List<JSONObject> list = this.baseMapper.getLineChart(pyInfo);
        LineChartRetDto lineChartRetDto = new LineChartRetDto();
        List<String> xData = new ArrayList<>();
        List<String> yData = new ArrayList<>();
        List<String> yData1 = new ArrayList<>();
        for (JSONObject json : list) {
            String x = json.getString("xData");
            BigDecimal y = json.getBigDecimal("yData");
            BigDecimal y1 = json.getBigDecimal("yData1");
            xData.add(x);
            yData.add(y.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
            yData1.add(y1.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
        }
        lineChartRetDto.setXData(xData);
        lineChartRetDto.setYData(yData);
        lineChartRetDto.setYData1(yData1);
        return lineChartRetDto;
    }
}
